﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CustomsSystem.BLL;
using CustomsSystem.Model;
using Maticsoft.Common;
using System.Data;

namespace WEB.plan
{
    public partial class planEdit : System.Web.UI.Page
    {
        planManage bll = new planManage();

        DataSet ds;

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!Page.IsPostBack)
            {
                #region 载入控件数据
                this.lbAddCus.Attributes.Add("onClick", "OpenChildWinCUS()");
                this.tbGency.Attributes.Add("onClick", "new WdatePicker()");
                this.tbCustomsNo.Attributes.Add("onClick", "OpenChildWindow()");
                this.tbContainerNo.Attributes.Add("onClick", "OpenChildWindow2()");
                BindCodeData(ddlInOut, "inoutType");
                BindCodeData(ddlTradeType, "tradeType");
                BindCodeData(ddlUnit1, "unitType");
                BindCodeData(ddlUnit2, "unitType");
                BindCodeData(ddlUnit3, "unitType");
                BindFlowInfo(ddlworkflowInfo, 1);
                BindFlowInfo(ddlworkflowInfoBJ, 2);
                #endregion
                if (Request.QueryString["ID"] != null)   //修改
                {
                    #region 数据载入
                    int id = Convert.ToInt32(Request.QueryString["ID"]);
                    btnEdit.Text = "修改";
                    //委托单号显示
                    lbsheet.Visible = true;
                    lbSheetValue.Text = id.ToString();
                    lbSheetValue.Visible = true;
                    ///*载入数据*/
                    T_plan myplan = new T_plan();
                    myplan = bll.GetModel(id);
                    ddlTypeId.SelectedIndex = ddlTypeId.Items.IndexOf(ddlTypeId.Items.FindByValue(myplan.typeID.ToString()));
                    ddlInOut.SelectedIndex = ddlInOut.Items.IndexOf(ddlInOut.Items.FindByValue(myplan.inOut.ToString()));
                    ddlworkflowInfo.SelectedIndex = ddlworkflowInfo.Items.IndexOf(ddlworkflowInfo.Items.FindByValue(myplan.InfoWKTypeIDbg.ToString()));
                    ddlworkflowInfoBJ.SelectedIndex = ddlworkflowInfo.Items.IndexOf(ddlworkflowInfoBJ.Items.FindByValue(myplan.InfoWKTypeIDbj.ToString()));
                    ddlTradeType.SelectedIndex = ddlTradeType.Items.IndexOf(ddlTradeType.Items.FindByValue(myplan.tradeType.ToString()));
                    //根据公司ID获取公司名字
                    CustomerManage cusBll = new CustomerManage();
                    Customer cusModel = cusBll.GetModel(myplan.cID);
                    string cusomerName = cusModel.CustomerName;
                    tbCid.Text = cusomerName;

                    tbGency.Text = myplan.agencyDate.ToString();
                    tbGoodsName.Text = myplan.goodsName;
                    tbweight.Text = myplan.grossWeight.ToString();
                    //======提取数量====
                    string str = myplan.No;
                    string[] strArry = str.Split(',');
                    for (int i = 0; i < strArry.Length; i++)
                    {
                        //初始化数据
                        int num = 0;
                        string result1 = "";
                        string result2 = "";
                        if (strArry[i].ToString() != "")
                        {
                            num = strArry[i].IndexOf("X");
                            result1 = strArry[i].Substring(0, num);
                            result2 = strArry[i].Substring(num + 1);

                            //判断绑定数据的位置
                            if (i == 0)
                            {
                                tbCount1.Text = result1;
                                ddlUnit1.SelectedIndex = ddlUnit1.Items.IndexOf(ddlUnit1.Items.FindByText(result2));
                                continue;
                            }
                            if (i == 1)
                            {
                                tbCount2.Text = result1;
                                ddlUnit2.SelectedIndex = ddlUnit2.Items.IndexOf(ddlUnit2.Items.FindByText(result2));
                                continue;
                            }
                            if (i == 2)
                            {
                                tbCount3.Text = result1;
                                ddlUnit3.SelectedIndex = ddlUnit3.Items.IndexOf(ddlUnit3.Items.FindByText(result2));
                                continue;
                            }
                        }
                    }

                    tbCustomsNo.Text = myplan.customsNo;
                    tbInspectionNo.Text = myplan.inspectionNo;
                    tbContractNo.Text = myplan.contractNo;
                    tbAgency.Text = myplan.agency;
                    tbshipCompany.Text = myplan.shipCompany;
                    tbRemark.Text = myplan.remark;
                    tbLadingBillNo.Text = myplan.ladingBillNo;
                    tbContainerNo.Text = myplan.containerNo;
                    tbHeadBillNo.Text = myplan.headLadingBillNo;
                    tbTransferNo1.Text = myplan.transferNo1;
                    tbTransferNo2.Text = myplan.transferNo2;
                    tbTransferNo3.Text = myplan.transferNo3;
                    tbFilingNo.Text = myplan.filingNo;
                    tbInvTitle.Text = myplan.invTilte;
                    tbInspection.Text = myplan.inspetionAgancy;
                    tbPO.Text = myplan.PO.ToString();
                    tbBatchNO.Text = myplan.BatchNO.ToString();
                    tbTestItem.Text = myplan.TestItem.ToString();
                    tbModel.Text = myplan.Model.ToString();
                    tbRegUnit.Text = myplan.RegisterUnit.ToString();
                    tbTransport.Text = myplan.Transport.ToString();
                    ckDG.Checked = myplan.DangerousGoods;
                    tbshipname.Text = myplan.shipName.ToString();
                    #endregion
                }

                else //新增
                {
                    btnEdit.Text = "增加";

                }
            }
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            #region 有效性判断

            string strErr = "";

            if (tbCid.Text.Trim() == "")
            {
                strErr += "请输入客户公司！\\n";
            }

            if (tbCount1.Text.Trim() != "")
            {
                if ((!PageValidate.IsDecimal(tbCount1.Text) && !PageValidate.IsNumber(tbCount1.Text)))//数量
                {
                    tbCount1.BorderColor = System.Drawing.Color.Red;
                    strErr += "数量格式错误！\\n";
                }
            }
            if (tbCount2.Text.Trim() != "")
            {
                if ((!PageValidate.IsDecimal(tbCount2.Text) && !PageValidate.IsNumber(tbCount2.Text)))//数量
                {
                    tbCount2.BorderColor = System.Drawing.Color.Red;
                    strErr += "数量格式错误！\\n";
                }
            }
            if (tbCount3.Text.Trim() != "")
            {
                if ((!PageValidate.IsDecimal(tbCount3.Text) && !PageValidate.IsNumber(tbCount3.Text)))//数量
                {
                    tbCount3.BorderColor = System.Drawing.Color.Red;
                    strErr += "数量格式错误！\\n";
                }
            }
            if (tbweight.Text.Trim() != "")
            {
                if ((!PageValidate.IsDecimal(tbweight.Text) && !PageValidate.IsNumber(tbweight.Text)))//数量
                {
                    tbweight.BorderColor = System.Drawing.Color.Red;
                    strErr += "数量格式错误！\\n";
                }
            }
            if (tbCustomsNo.Text.Trim().Length >= 450)
            {
                strErr += "报关单号字数超过规定长度！\\n";
            }
            if (tbContainerNo.Text.Trim().Length >= 999)
            { strErr += "柜号文字超过规定长度!\\n"; }
            if (tbRemark.Text.Trim().Length > 250)
            { strErr += "备注文字超过规定长度!\\n"; }

            if (strErr != "")
            {
                MessageBox.Show(this, strErr);
                return;
            }
            #endregion

            #region 数据录入
            //模板判断
            if (ddlworkflowInfo.SelectedValue.ToString() == "" || ddlworkflowInfoBJ.SelectedValue.ToString() == "")
            {
                MessageBox.Show(this, "没有录入的模板，请设置模板！");
                return;
            }

            CustomsSystem.Model.T_plan myplan = new CustomsSystem.Model.T_plan();//获取plant的ID
            int plantID = Convert.ToInt32(lbSheetValue.Text.ToString().Trim());
            if (plantID != 0)
            {
                bll.GetModel(plantID);
            }

            myplan.planID = plantID;
            myplan.typeID = Convert.ToInt32(ddlTypeId.SelectedValue);
            myplan.inOut = Convert.ToInt32(ddlInOut.SelectedValue);
            myplan.InfoWKTypeIDbg = Convert.ToInt32(ddlworkflowInfo.SelectedValue);
            myplan.InfoWKTypeIDbj = Convert.ToInt32(ddlworkflowInfoBJ.SelectedValue);
            //根据公司名字获取公司ID
            CustomerManage cusBll = new CustomerManage();
            List<Customer> cusModels = cusBll.GetModelList("CustomerName='" + tbCid.Text.Trim() + "'");
            int cusID;
            if (cusModels.Count != 0)
            {
                cusID = cusModels[0].ID;
            }
            else
            {
                cusID = 0;
                MessageBox.Show(this, "该公司不存在，请确认"); //error["cusID"] = "该公司不存在，请确认";
                return;
            }

            myplan.cID = cusID;
            //==========根据模板取货物ID===============
            WorkflowManage wfMan = new WorkflowManage();
            Info_workflowMaster model;

            if (ddlworkflowInfo.SelectedValue != "-1")
            {
                model = wfMan.GetModelMaster(Convert.ToInt32(ddlworkflowInfo.SelectedValue));
            }
            else
            {
                model = wfMan.GetModelMaster(Convert.ToInt32(ddlworkflowInfoBJ.SelectedValue));
            }
            int goodstype = 0;
            if (model.goodsTypeID != null) goodstype = (int)model.goodsTypeID;
            myplan.goodsType = goodstype;

            if (tbGency.Text != "")
            {
                myplan.agencyDate = Convert.ToDateTime(tbGency.Text.Trim()).Date;
            }
            if (tbweight.Text.ToString().Trim() != "")
            {
                myplan.grossWeight = Convert.ToDecimal(tbweight.Text);
            }
            myplan.goodsName = tbGoodsName.Text.Trim();
            myplan.No = GetCount();
            myplan.shipName = tbshipname.Text.Trim();

            if (tbCustomsNo.Text.Trim() != "")
                myplan.customsNo = tbCustomsNo.Text.Trim();

            if (tbInspectionNo.Text.Trim() != "")
                myplan.inspectionNo = tbInspectionNo.Text.Trim();

            myplan.contractNo = tbContractNo.Text.Trim();
            myplan.agency = tbAgency.Text.Trim();
            myplan.shipCompany = tbshipCompany.Text.Trim();
            myplan.remark = tbRemark.Text;
            myplan.ladingBillNo = tbLadingBillNo.Text.Trim();
            myplan.containerNo = tbContainerNo.Text.Trim();
            myplan.headLadingBillNo = tbHeadBillNo.Text.Trim();
            if (tbTransferNo1.Text.Trim() != "")
                myplan.transferNo1 = tbTransferNo1.Text.Trim();

            if (tbTransferNo2.Text.Trim() != "")
                myplan.transferNo2 = tbTransferNo2.Text.Trim();

            if (tbTransferNo3.Text.Trim() != "")
                myplan.transferNo3 = tbTransferNo3.Text.Trim();


            myplan.filingNo = tbFilingNo.Text.Trim();
            myplan.invTilte = tbInvTitle.Text.Trim();
            myplan.inspetionAgancy = tbInspection.Text.Trim();
            myplan.PO = tbPO.Text.Trim();
            myplan.BatchNO = tbBatchNO.Text.Trim();
            myplan.TestItem = tbTestItem.Text.Trim();
            myplan.Model = tbModel.Text.Trim();
            myplan.RegisterUnit = tbRegUnit.Text.Trim();
            myplan.Transport = tbTransport.Text.Trim();
            myplan.DangerousGoods = ckDG.Checked;
            myplan.tradeType = Convert.ToInt32(ddlTradeType.SelectedValue);

            //录入员及日期处理
            myplan.inputEmpNo = Session["EmpNo"].ToString();
            myplan.inputDate = DateTime.Now;

            #endregion
            
            #region 写入

            if (myplan.planID <= 0)//增加记录
            {
                int newid = bll.Add(myplan);
                if (newid > 0)
                {
                    MessageBox.ShowAndRedirect(this, "增加成功", "planView.aspx");
                    return;
                }
                else
                { MessageBox.Show(this, "增加失败"); }
            }
            else     //修改记录
            {
                if (bll.Update(myplan))
                {
                    MessageBox.ShowAndRedirect(this, "修改成功", "planView.aspx");
                    return;
                }
                else
                {
                    MessageBox.Show(this, "修改失败");
                    return;
                }
            }
            #endregion
        }

        /// <summary>
        /// 获取制定代码类型绑定到控件上
        /// </summary>
        /// <param name="ddl"></param>
        private void BindCodeData(DropDownList ddl, string codeType)
        {
            CodeManage codeBll = new CodeManage();
            List<Info_code> codeModels = codeBll.GetModelList("codeType='" + codeType + "'");
            foreach (Info_code aCode in codeModels)
            {
                ddl.Items.Add(new ListItem(aCode.codeName, aCode.codeID.ToString()));
            }
        }

        /// <summary>
        /// 获取所有工作流模板
        /// </summary>
        /// <param name="ddl"></param>
        private void BindFlowInfo(DropDownList ddl, int type)
        {
            WorkflowManage wfBll = new WorkflowManage();
            List<Info_workflowMaster> wfModels = wfBll.GetModelListMaster("");
            foreach (Info_workflowMaster aflow in wfModels)
            {
                if (aflow.sheetTypeID == type)
                    ddl.Items.Add(new ListItem(aflow.WKTypeName, aflow.infoWKTypeID.ToString()));
            }
        }


        [System.Web.Services.WebMethod]
        [System.Web.Script.Services.ScriptMethod]
        public static string[] GetCustomersName(string prefixText, int count)
        {
            CustomerManage cusManage = new CustomerManage();
            List<string> strArray = new List<string>();
            //string[] strArray = { "中国石油公司","中顺洁柔","中山技术",
            //"捷达捷达捷达达","时代复分","幅度为爱"};
            List<Customer> cusList = cusManage.GetModelList("");
            foreach (Customer aCus in cusList)
            {
                strArray.Add(aCus.CustomerName);
            }
            return (from m in strArray
                    where m.Contains(prefixText)
                    select m).Take(count).ToArray();
        }
        /// <summary>
        /// 获取数量值
        /// </summary>
        /// <returns></returns>
        public string GetCount()
        {
            string count = "";

            if (tbCount1.Text.Trim() != "")
            {
                count = tbCount1.Text + "X" + ddlUnit1.SelectedItem.Text;
                if (tbCount2.Text.Trim() != "")
                {
                    count = count + "," + tbCount2.Text + "X" + ddlUnit2.SelectedItem.Text;
                    if (tbCount3.Text.Trim() != "")
                    {
                        count = count + "," + tbCount3.Text + "X" + ddlUnit3.SelectedItem.Text;
                    }
                }
            }


            return count;
        }
        /// <summary>
        /// 客户名改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void tbCid_TextChanged(object sender, EventArgs e)
        {
            CustomerManage cusBll = new CustomerManage();
            List<Customer> cusModels = cusBll.GetModelList("CustomerName='" + tbCid.Text.Trim() + "'");
            if (cusModels.Count != 0)
            {
                tbInvTitle.Text = cusModels[0].Invoice;
            }
        }

        /// <summary>
        /// 模板名称改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlTypeId_SelectedIndexChanged(object sender, EventArgs e)
        {
            string selectIndex = ((DropDownList)sender).SelectedValue;
            //报关^
            if (selectIndex == "1" || selectIndex == "4" || selectIndex == "5")
            {
                lblBJ.Visible = false;
                ddlworkflowInfoBJ.Visible = false;

                lblBG.Visible = true;
                ddlworkflowInfo.Visible = true;
                lblBG.Text = "模板：";

                if (ddlworkflowInfo.Items.Contains(ddlworkflowInfo.Items.FindByValue("-1")))
                {
                    ddlworkflowInfo.Items.Remove(ddlworkflowInfo.Items.FindByValue("-1"));
                }

                if (!ddlworkflowInfoBJ.Items.Contains(ddlworkflowInfoBJ.Items.FindByValue("-1")))
                {
                    ddlworkflowInfoBJ.Items.Insert(0, new ListItem("--请选择--", "-1"));
                }
                ddlworkflowInfoBJ.SelectedValue = "-1";

            }//报检
            else if (selectIndex == "2")
            {
                lblBJ.Visible = true;
                ddlworkflowInfoBJ.Visible = true;
                lblBJ.Text = "模板：";

                lblBG.Visible = false;
                ddlworkflowInfo.Visible = false;

                if (ddlworkflowInfoBJ.Items.Contains(ddlworkflowInfoBJ.Items.FindByValue("-1")))
                {
                    ddlworkflowInfoBJ.Items.Remove(ddlworkflowInfoBJ.Items.FindByValue("-1"));
                }
                if (!ddlworkflowInfo.Items.Contains(ddlworkflowInfo.Items.FindByValue("-1")))
                {
                    ddlworkflowInfo.Items.Insert(0, new ListItem("--请选择--", "-1"));
                }
                ddlworkflowInfo.SelectedValue = "-1";

                ddlworkflowInfoBJ.Items.Clear();
                BindFlowInfo(ddlworkflowInfoBJ, int.Parse(selectIndex));
                return;

            }//报关报检
            else if (selectIndex == "3" || selectIndex == "6")
            {
                lblBJ.Visible = true;
                ddlworkflowInfoBJ.Visible = true;
                lblBJ.Text = "报检：";

                lblBG.Visible = true;
                ddlworkflowInfo.Visible = true;
                lblBG.Text = "报关：";

                if (ddlworkflowInfoBJ.Items.Contains(ddlworkflowInfoBJ.Items.FindByValue("-1")))
                {
                    ddlworkflowInfoBJ.Items.Remove(ddlworkflowInfoBJ.Items.FindByValue("-1"));
                }

                if (ddlworkflowInfo.Items.Contains(ddlworkflowInfo.Items.FindByValue("-1")))
                {
                    ddlworkflowInfo.Items.Remove(ddlworkflowInfo.Items.FindByValue("-1"));
                }
                if (selectIndex == "3")
                {
                    ddlworkflowInfo.Items.Clear();
                    BindFlowInfo(ddlworkflowInfo, 1);
                    ddlworkflowInfoBJ.Items.Clear();
                    BindFlowInfo(ddlworkflowInfoBJ, 2);
                }
                else
                {
                    ddlworkflowInfo.Items.Clear();
                    BindFlowInfo(ddlworkflowInfo, int.Parse(selectIndex));
                    ddlworkflowInfoBJ.Items.Clear();
                    BindFlowInfo(ddlworkflowInfoBJ, int.Parse(selectIndex));
                }
                return;
            }
            ddlworkflowInfo.Items.Clear();
            BindFlowInfo(ddlworkflowInfo, int.Parse(selectIndex));
        }

        protected void ddlworkflowInfo_SelectedIndexChanged(object sender, EventArgs e)
        {
            //更新货物类型
        }
    }
}